package br.ucb.jogo.negocioDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import br.ucb.jogo.conexao.MyConnection;
import br.ucb.jogo.interfaces.DAO;
import br.ucb.jogo.negocio.Usuario;

public class UsuarioDAO implements DAO{

	@Override
	public boolean insert(Object t) {
		
		Usuario u = (Usuario) t;
		
		String sql = "INSERT INTO usuarios(nome, email, senha, tipo, login) VALUES (?,?,?,?,?);";
		Connection con = null;
		PreparedStatement ps = null;
		int retorno = 0;
		try {
			con = MyConnection.init();
			ps = con.prepareStatement(sql);
			ps.setString(1,u.getNome());
			ps.setString(2,u.getEmail());
			ps.setString(3, u.getSenha());
			ps.setInt(4,u.getTipo().getNumber());
			ps.setString(5, u.getLogin());
			retorno = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return retorno == 0 ? false:true;		
	}

	@Override
	public boolean delete(Object t) {
		String sql = "DELETE FROM usuarios WHERE idUsuarios = ?;";
		Connection con = null;
		PreparedStatement ps = null;
		int retorno = 0;
		Usuario u = (Usuario) t;
		try {
			con = MyConnection.init();
			ps = con.prepareStatement(sql);
			ps.setInt(1,u.getId());
			retorno = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return retorno == 0 ? false:true;
	}

	@Override
	public List<Usuario> select() throws SQLException {
		String sql = "SELECT * FROM usuarios;";
		Connection con = MyConnection.init();
		Statement stm = con.createStatement();
		ResultSet rs = null;
		List<Usuario> usuarios = new ArrayList<Usuario>();
		rs = stm.executeQuery(sql);
		while(rs.next()){
			usuarios.add(getUsuario(rs));
		}
		return usuarios;
	}
	
	public Usuario getUsuario(ResultSet rs) throws SQLException{
		return new Usuario(rs.getInt(1), rs.getString(2), rs.getString(6), rs.getString(4), rs.getString(3), null);
	}

	@Override
	public boolean update(Object t) throws SQLException {
		Usuario u = (Usuario) t;
		String sql = "UPDATE usuarios SET nome = ?, email = ?, senha = ?, tipo = ?, login = ? WHERE idUsuarios = ?";
		Connection con = null;
		PreparedStatement ps = null;
		int retorno = 0;
		try {
			con = MyConnection.init();
			ps = con.prepareStatement(sql);
			ps.setString(1,u.getNome());
			ps.setString(2,u.getEmail());
			ps.setString(3, u.getSenha());
			ps.setInt(4, u.getTipo().getNumber());
			ps.setString(5, u.getLogin());
			ps.setInt(6, u.getId());
			retorno = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return retorno == 0 ? false:true;
	}

}
